from forms import StudioForm,ChoiceForm
from common.db_tools import from_dict
from models import Studio
from django.core.urlresolvers import reverse
from api.ps import PS
from api.pts import PTS
import app_info
import resource
from common.db_tools import to_dict
from models import Log,AppModel
import json
from common.db_tools import get_or_none
import time
import deploy

from tasks import freeze_studio_with_celery,update_studio_appset_with_celery

def get_globals():
    return globals()


def add_studio(name):
    """
    @name: str: studio name
    """
    form = ChoiceForm({'name':name})
    if form.is_valid():
        s=Studio.objects.create(name=name)
        update_studio_appset_with_celery.delay(name)
        return {'status':'ok','edit_url':reverse('edit_studio',args=(s.pk,))}
    else:
        return {'errors':form.errors}


def save_studio(studio):
    """
    @studio: dict : 
    """
    form=StudioForm(studio)

    if form.is_valid():
        studio.update(form.cleaned_data )
        studio_obj=from_dict(studio)
        studio_obj.save()
        # freeze_studio_with_celery(studio_obj)
        return {'status':'success'}
    else:
        return {'errors':form.errors}
    

    
def get_studio_apps(studio):
    """
    @studio:str: studio name
    """
    studio_obj = Studio.objects.get(name=studio)
    while studio_obj.status.appset=='no':   # wate for celery done task
        time.sleep(2)                       # this possibility might very low
        studio_obj = Studio.objects.get(name=studio)
        
    if studio_obj.status.appset!='yes':     # means get appsets for pts or ps has error
        raise UserWarning,studio_obj.status.appset
    ls = [to_dict(app,filt_attr=_change_screenshot) for app in studio_obj.appmodel_set.exclude(status='deactive')]
    for app in ls:
        app['log']=[to_dict(log) for log in Log.objects.filter(key=app.get('sku'),category='app.update').order_by('-time')]
    
    return ls

def _change_screenshot(instance):
    if instance.screenshots:
        return {'screenshots': instance.screenshots.rstrip(';').split(';')}
    else:
        return {}

# def get_app_resource(media_url):
    # return resource.get_app_resource(media_url)

# def get_app_meta(sku):
    # ps=PS()
    # meta=ps.get_app_meta(sku)
    # return meta

def update_studio(name):
    app_info.update_studio_appset(name)
    return {'status':'success'}

def update_app(sku,studio_name):
    app_info.update_app(sku, studio_name)
    return {'status':'success'}


def get_app(sku):
    try:
        app =AppModel.objects.get(sku=sku)
        dc= to_dict(app,filt_attr=_change_screenshot)
        dc['log']=[to_dict(log) for log in Log.objects.filter(key=sku,category='app.update').order_by('-time')]
        return dc
    except AppModel.DoesNotExist as e:
        raise UserWarning,str(e)

def save_app(app):
    app_dc = json.loads(app)
    app_obj=from_dict(app_dc)
    app_obj.studio.save()
    app_obj.save()
    return {'status':'success'}

def get_studio_log(studio_name):

    logs=Log.objects.filter(category__startswith='studio.',key=studio_name).order_by('-time')
    logs=[to_dict(log) for log in logs]
    return logs


def deploy_studio_manual(studio_name):
    #try:
    studio=Studio.objects.get(name=studio_name)
    deploy.deploy_studio(studio)
    return {'status':'success'}
    #except Exception as e:
        #raise UserWarning,'there is error : %s'%(repr(e))
    

